<template>
	<!-- components/count-down/index.wxml -->
	<text class="my-class">{{ text }}</text>
</template>

<script>
	// components/count-down/index.js
	export default {
		data() {
			return {
				text: '--:--:--',
				interval: null
			};
		},
		externalClasses: ['my-class'],
		/**
		 * 组件的属性列表
		 */
		props: {
			serverTime: {
				type: Number,
				default: 0
			},
			startTime: {
				type: Number,
				default: 0
			},
			formatType: {
				// 格式化样式，0默认HH:mm:ss，HH时mm分ss秒
				type: String,
				default: '0'
			}
		},
		watch: {
			serverTime: function() {
				this.startCountdown();
			}
		},
		created() {
			this.startCountdown();
		},
		destroyed: function() {
			// 在组件实例被从页面节点树移除时执行
			clearInterval(this.interval);
		},
		/**
		 * 组件的方法列表
		 */
		methods: {
			startCountdown() {
				// 在 serverTime 或者 startTime 被设置时，执行这个函数
				if (0 == this.serverTime || 0 == this.startTime) {
					return;
				}
				if (this.interval) {
					clearInterval(this.interval);
				}
				let iServerTime = parseInt(this.serverTime);
				let iStartTime = parseInt(this.startTime);
				let diffTime = iStartTime - iServerTime;
				let text = ''; // 如果活动未结束，对时间进行处理

				if (diffTime > 0) {
					let day;
					let hou;
					let min;
					let sec;
					let interval = setInterval(() => {
						diffTime--;

						if (0 == diffTime) {
							clearInterval(this.interval);
							this.$emit('finished');
						}

						text = '';
						day = parseInt(diffTime / 86400);
						hou = parseInt(diffTime / 3600 % 24);
						min = parseInt(diffTime / 60 % 60);
						sec = parseInt(diffTime % 60);

						if (0 < day) {
							text +=
								`${day}天${hou.toString().padStart(2, '0')}时${min.toString().padStart(2, '0')}分`;
						} else {
							if (0 < hou) {
								if (1 == this.formatType) {
									text += `${hou.toString().padStart(2, '0')}时`;
								} else {
									text += `${hou.toString().padStart(2, '0')}:`;
								}
							}

							if (1 == this.formatType) {
								text +=
									`${min.toString().padStart(2, '0')}分${sec.toString().padStart(2, '0')}秒`;
							} else {
								text +=
									`${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
							}
						} // console.log(text);


						this.setData({
							text: text
						});
					}, 1000);
					this.setData({
						interval
					});
				}
			}
		},
	};
</script>
<style lang="scss">
	/* components/count-down/index.wxss */
</style>
